package miiteen.demo.utils;

import miiteen.common.json.JsonUtil;
import miiteen.core.string.StringTool;
import miiteen.module.pubtable.beans.PubTable;
import miiteen.module.pubtable.service.PubTableService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 通用工具类
 * author: 曾捍君
 * date: 2019-1-14
 */
@Service
public class CommonUtil {

    @Autowired
    private PubTableService pubTableService;

    /**
     * 处理模糊查询条件
     *
     * @param map  查询条件集合
     * @param keys 查询条件关键字
     */
    public void handleLikeSearch(Map<String, Object> map, String... keys) {
        if (map == null || map.size() == 0) return;
        if (keys == null || keys.length == 0) return;

        for (String key : keys) {
            if (map.containsKey(key)) {
                String v = map.get(key).toString();
                if (StringTool.IsEmptyOrNull(v)) continue;

                map.remove(key);
                map.put(key, "%" + v + "%");
            }
        }
    }

    /**
     * 获取代码表数据
     *
     * @param tableName 表名
     * @return
     */
    public String getPubTable4List(String tableName) {
        Map<String, Object> map = new HashMap<>();
        map.put("tableName", tableName);
        map.put("orderField", "showOrder");
        List<PubTable> list = pubTableService.findListByMap(map);
        if (list == null || list.size() == 0) return null;

        List<Map<String, Object>> result = new ArrayList<>();
        for (PubTable pt : list) {
            Map<String, Object> mp = new HashMap<>();
            mp.put("id", pt.getId());
            mp.put("name", pt.getName());
            result.add((mp));
        }

        return JsonUtil.toJsonStr(result);
    }

    /**
     * 获取随机数字符串
     *
     * @param charCount 字符串长度
     * @return
     */
    public String getRandom(int charCount) {
        String charValue = "";
        for (int i = 0; i < charCount; i++) {
            char c = (char) (randomInt(0, 10) + '0');
            charValue += String.valueOf(c);
        }
        return charValue;
    }

    /**
     * 获取随机数
     *
     * @param from 下限
     * @param to   上限
     * @return
     */
    private static int randomInt(int from, int to) {
        if (from == to) return from;

        Random r = new Random();
        return from + r.nextInt(to - from);
    }

}
